﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json.Linq;
using Qianke.Core.Common;
using Qianke.Core.Common.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;

namespace Qianke.Core.Saas.HttpApi.Client.Common
{
    public interface ISaasResultHttpMessageHandler : ITransientDependency
    {
    }

    public class SaasResultHttpMessageHandler : DelegatingHandler, ISaasResultHttpMessageHandler
    {
        public IServiceProvider serviceProvider { set; get; }

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            // 获取请求作用域的服务提供器
            var httpContextAccessor = serviceProvider.GetService<IHttpContextAccessor>();
            // 使用请求作用域的服务提供器
            var tokenInfo = httpContextAccessor.HttpContext?.RequestServices?.GetRequiredService<ITokenInfo>();
            if (tokenInfo.Id > 0)
                request.Headers.Authorization = new AuthenticationHeaderValue("SAASTOKEN", TokenHelper.CreateToken(tokenInfo));

            var response = await base.SendAsync(request, cancellationToken);
            // 拦截返回值并进行处理
            if (response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsStringAsync();
                var result = content.ToObject<ReturnInfoData<JToken>>();
                if (result.resultcode != "200")
                    throw new Exception(result.resultcontent);
                // 修改返回值格式或进行其他处理
                response.Content = new StringContent(result.data.ToJson());
            }
            return response;
        }
    }
}
